﻿using NewCodeAPI.Models;
using NewCodeAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewCodeAPI.Service;
using Lazy.Captcha.Core;

namespace Service
{
    public class UserLoginService
    {
        private readonly EncryptionService _encryptionService;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ICaptcha _captcha;
        public UserLoginService(EncryptionService encryptionService, IHttpContextAccessor httpContextAccessor, ICaptcha captcha)
        {
            _encryptionService = encryptionService;
            _httpContextAccessor = httpContextAccessor;
            _captcha = captcha;
        }
        public MsgInfo LoginUser(string username, string password, string code)
        {
            // Replace with your actual authentication logic
            //return username == "user" && password == "password";

            using (NdlsDBContext context = new NdlsDBContext())
            {
                SmPerson user = context.SmPerson.FirstOrDefault(u => u.Username == username);

                if (user == null)
                {
                    // 用户不存在的情况
                    return new MsgInfo { Status = "Error", Msg = "该用户不存在用户名" };
                }

                // 解码Base64的存储密码
                //byte[] storedPasswordBytes = Convert.FromBase64String(user.Password ?? "");
                // 提取IV和加密的密码部分
                //byte[] iv = storedPasswordBytes.Take(16).ToArray();
                // 使用存储的IV和密钥对用户提供的密码进行加密
                string encryptedUserPassword = _encryptionService.Encrypt(password);

                // 将加密后的用户提供的密码与存储的密码进行比较
                //if (encryptedUserPassword == Convert.ToBase64String(storedPasswordBytes))
                if (encryptedUserPassword == user.Password)
                {
                    string id = "wdh007";
                    if (_captcha.Validate(id, code))
                    {
                        var token = JwtHelper.IssueJwt(user);
                        HttpContext httpContext = _httpContextAccessor.HttpContext;
                        httpContext.Response.Cookies.Append("Token", token, new CookieOptions
                        {
                            Expires = DateTime.Now.AddMinutes(20)
                        });
                        // 密码正确，返回成功消息
                        return new MsgInfo { Status = "Success", Msg = "登录成功", Token = token };
                    }
                    else
                    {
                        return new MsgInfo { Status = "Error", Msg = "验证码错误" };
                    }
                }
                else
                {
                    // 密码不正确，返回通用错误消息
                    return new MsgInfo { Status = "Error", Msg = "用户名或密码不正确" };
                }
            }
            
        }
    }

}
